package com.ayuku.commons;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.wb.swt.SWTResourceManager;

/**
 * 
 * @author putu kusuma <putukn@gmail.com>
 *
 */
public abstract class ListFormReportMaster extends
		org.eclipse.swt.widgets.Dialog {
	protected Shell dialogShell;
	protected Table tableData = null;
	private Button btnFind;
	private Label lblMessage;
	private Button btnClear;
	private Label lblRecordMsg;
	private Button btnPrint;
	private Label lblSearch;
	private Text fSearch;
	private Button btnReload;
	private Button btnExport;
	private Composite pnlButtonCmd;
	private Composite pnlData;
	private Composite pnlSearch;
	private String funcId;

	public String getFuncId() {
		return funcId;
	}

	public void setFuncId(String funcId) {
		this.funcId = funcId;
	}

	private Logger LOG = Logger.getLogger(ListFormReportMaster.class.getName());

	public ListFormReportMaster(final Shell parent, final int style) {
		super(parent, style);
	}

	public final void open() {
		try {
			final Shell parent = getParent();
			dialogShell = new Shell(parent, SWT.DIALOG_TRIM | SWT.RESIZE);
	

			final FormLayout dialogShellLayout = new FormLayout();
			dialogShell.setBackground(SWTResourceManager
					.getColor(215, 213, 253));

			dialogShell.setLayout(dialogShellLayout);
			dialogShell.layout();
			dialogShell.pack();
			dialogShell.setSize(757, 412);
			dialogShell.setText("Test");
			dialogShell.setLocation(60, 100);

			pnlButtonCmd = new Composite(dialogShell, SWT.NONE);

			FillLayout composite3Layout = new FillLayout(
					org.eclipse.swt.SWT.HORIZONTAL);
			composite3Layout.spacing = 4;
			pnlButtonCmd.setLayout(composite3Layout);

			FormData pnlButtonLData = new FormData();
			pnlButtonLData.width = 251;
			pnlButtonLData.height = 32;
			pnlButtonLData.left = new FormAttachment(0, 1000, 4);
			pnlButtonLData.top = new FormAttachment(0, 1000, 6);
			pnlButtonCmd.setLayoutData(pnlButtonLData);
			pnlButtonCmd.setBackground(SWTResourceManager.getColor(215, 213,
					253));

			btnReload = new Button(pnlButtonCmd, SWT.PUSH | SWT.CENTER);
			btnReload
					.setToolTipText("Tombol 'Refresh' untuk merefresh/mereload data terbaru dari database ");

			btnReload.setImage(SWTResourceManager.getImage(ListFormReportMaster.class, "/images/form/database_refresh.png"));
			btnReload.setSize(34, 34);
			btnReload.setCursor(SWTResourceManager.getCursor(SWT.CURSOR_HAND));
			btnReload.setBackground(SWTResourceManager.getColor(215, 213, 253));
			btnReload.setText("Refresh");

			btnExport = new Button(pnlButtonCmd, SWT.PUSH | SWT.CENTER);
			btnExport
					.setToolTipText("Tombol 'View' untuk menampilkan detail baris yang dipilih.");
			btnExport.setImage(SWTResourceManager.getImage(ListFormReportMaster.class, "/images/form/page_excel.png"));
			btnExport.setCursor(SWTResourceManager.getCursor(SWT.CURSOR_HAND));
			btnExport.setBackground(SWTResourceManager.getColor(215, 213, 253));
			btnExport.setText("Export");
			btnExport.addSelectionListener(new SelectionAdapter() {
				public void widgetSelected(SelectionEvent evt) {
					btnExportWidgetSelected(evt);
				}
			});

			btnReload.addSelectionListener(new SelectionAdapter() {
				public void widgetSelected(SelectionEvent evt) {
					btnReloadWidgetSelected(evt);
				}
			});
			btnPrint = new Button(pnlButtonCmd, SWT.PUSH | SWT.CENTER);

			btnPrint.setImage(SWTResourceManager
					.getImage("images/form/page_excel.png"));
			btnPrint.setSize(34, 26);
			btnPrint.setToolTipText("Print Report");
			btnPrint.setCursor(SWTResourceManager.getCursor(SWT.CURSOR_HAND));
			btnPrint.addSelectionListener(new SelectionAdapter() {
				public void widgetSelected(SelectionEvent evt) {
					btnPrintWidgetSelected(evt);
				}
			});

			pnlSearch = new Composite(dialogShell, SWT.NONE);
			pnlSearch.setLayout(new GridLayout(5, false));

			FormData pnlSearchLData = new FormData();
			pnlSearchLData.width = 749;
			pnlSearchLData.height = 35;
			pnlSearchLData.left = new FormAttachment(0, 1000, 0);
			pnlSearchLData.top = new FormAttachment(0, 1000, 42);
			pnlSearchLData.right = new FormAttachment(1000, 1000, 0);
			pnlSearch.setLayoutData(pnlSearchLData);
			pnlSearch.setBackground(SWTResourceManager.getColor(191, 211, 249));
			lblSearch = new Label(pnlSearch, SWT.NONE);
			lblSearch.setText("Search :");

			lblSearch.setAlignment(SWT.RIGHT);

			lblSearch.setBackground(SWTResourceManager.getColor(191, 211, 249));
	
			fSearch = new Text(pnlSearch, SWT.SEARCH);
			fSearch.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1));
			fSearch.setText("");
	
			fSearch
					.setToolTipText("Kotak 'Pencarian' ketikkan data yang akan di cari di kotak ini kemudian tekan enter atau tekan tombol 'Pencarian'");
			fSearch.addKeyListener(new KeyAdapter() {
				public void keyReleased(KeyEvent evt) {
					fSearchKeyReleased(evt);
				}
			});
			btnFind = new Button(pnlSearch, SWT.PUSH | SWT.CENTER);

			btnFind.setCursor(SWTResourceManager.getCursor(SWT.CURSOR_HAND));
			btnFind.setBackground(SWTResourceManager.getColor(191, 211, 249));
	
			btnFind
					.setToolTipText("Tombol 'Search' tekan tombol ini untuk memulai pencarian data");
			btnFind.setText(" Go ");
			btnFind.addSelectionListener(new SelectionAdapter() {
				public void widgetSelected(SelectionEvent evt) {
					btnFindWidgetSelected(evt);
				}
			});
			btnClear = new Button(pnlSearch, SWT.PUSH | SWT.CENTER);
			
						btnClear.setBackground(SWTResourceManager.getColor(191, 211, 249));
						
									btnClear
											.setToolTipText("Tombol 'Clear search' untuk menghapus kriteria pencarian yang diketikkan di kotak pencarian dan menampilkan data tanpa kriteria.");
									btnClear.setText(" Clear ");
									btnClear.addSelectionListener(new SelectionAdapter() {
										public void widgetSelected(SelectionEvent evt) {
											btnClearWidgetSelected(evt);
										}
									});
			lblRecordMsg = new Label(pnlSearch, SWT.NONE);
			lblRecordMsg.setAlignment(SWT.RIGHT);

			lblRecordMsg.setBackground(SWTResourceManager.getColor(192, 192,
					192));
	

			pnlData = new Composite(dialogShell, SWT.NONE);

			final FillLayout composite2Layout = new FillLayout(
					org.eclipse.swt.SWT.HORIZONTAL);
			composite2Layout.marginHeight = 6;
			composite2Layout.marginWidth = 6;
			pnlData.setLayout(composite2Layout);

			final FormData pnlDataLData = new FormData();
			pnlDataLData.width = 749;
			pnlDataLData.height = 280;
			pnlDataLData.left = new FormAttachment(0, 1000, 0);
			pnlDataLData.top = new FormAttachment(0, 1000, 77);
			pnlDataLData.right = new FormAttachment(1000, 1000, 0);
			pnlDataLData.bottom = new FormAttachment(1000, 1000, -21);
			pnlData.setLayoutData(pnlDataLData);
			pnlData.setBackground(SWTResourceManager.getColor(215, 213, 253));
			tableData = new Table(pnlData, SWT.VIRTUAL | SWT.MULTI
					| SWT.FULL_SELECTION | SWT.BORDER | SWT.V_SCROLL
					| SWT.H_SCROLL);
			tableData.addKeyListener(new KeyAdapter() {
				public void keyPressed(KeyEvent evt) {
					tableDataKeyPressed(evt);
				}
			});

			tableData.addMouseListener(new MouseAdapter() {
				public void mouseDoubleClick(MouseEvent evt) {
					tableDataMouseDoubleClick(evt);
				}
			});

			lblMessage = new Label(dialogShell, SWT.NONE);

			FormData lblMessageLData = new FormData();
			lblMessageLData.left = new FormAttachment(0, 1000, 7);
			lblMessageLData.width = 649;
			lblMessageLData.height = 18;
			lblMessageLData.bottom = new FormAttachment(1000, 1000, -3);
			lblMessageLData.right = new FormAttachment(1000, 1000, -93);
			lblMessage.setLayoutData(lblMessageLData);
			lblMessage
					.setBackground(SWTResourceManager.getColor(215, 213, 253));

			final boolean dt = createTableColumn(getTableData());
			if (dt) {
				loadDataThread();
			}

			additionalProcess();
			btnPrint.setVisible(false);

			tableData.setFont(SWTResourceManager.getFont("Arial", 9, 0, false,
					false));
			dialogShell.setImage(SWTResourceManager.getImage(ListFormReportMaster.class, "/images/form/application_view_tile.png"));

			dialogShell.open();

			Display display = dialogShell.getDisplay();

			while (!dialogShell.isDisposed()) {
				if (!display.readAndDispatch()) {
					display.sleep();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			LOG.info(e.getMessage());
			Util.showMsgBox("Gagal load: " + e.getMessage(), 1,
					getDialogShell());
		}
	}

	public void loadDataThread() {
		try {
			loadSearchData();
			lblMessage.setText("Jumlah data:" + tableData.getItemCount());
		} catch (Exception e) {
			e.printStackTrace();
			Util.showMsgBox("Gagal load: " + e.getMessage(), 1,
					getDialogShell());
		}
		fSearch.setFocus();
	}

	public final boolean createTableColumn(Table tableData) {
		tableData.setLinesVisible(true);
		tableData.setHeaderVisible(true);

		boolean rtrValue = true;
		final String[] titles = getColumCaption();

		if (titles == null) {
			rtrValue = false;
		}

		for (int i = 0; i < titles.length; i++) {
			TableColumn column = new TableColumn(tableData, SWT.NONE);
			column.setText(titles[i]);
			if (i == 0) {
				column.setResizable(false);
			}
		}

		int[] col = getColumWidth();

		if (col == null) {
			rtrValue = false;
		}

		for (int i = 0; i < col.length; i++) {
			tableData.getColumn(i).setWidth(col[i]);
		}

		return rtrValue;
	}

	abstract protected String[] getColumCaption();

	abstract protected int[] getColumWidth();

	abstract protected void populateTable(String sqlDml) throws Exception;

	abstract protected void loadAllData() throws Exception;

	abstract protected void loadSearchData() throws Exception;

	abstract protected Integer doDelete(List<String> id) throws Exception;

	abstract protected void fillTable(Object obj, TableItem item);

	abstract protected void showEditForm();

	abstract public void printPreview();

	abstract public void showAddForm();

	abstract public void additionalProcess();

	abstract public void doExport();

	private final void btnReloadWidgetSelected(SelectionEvent evt) {
		loadDataThread();
	}

	private final void btnPrintWidgetSelected(SelectionEvent evt) {
		printPreview();
	}

	private final void btnFindWidgetSelected(SelectionEvent evt) {
		loadDataThread();
		fSearch.setFocus();
	}

	public final Shell getDialogShell() {
		return dialogShell;
	}

	public final void setDialogShell(Shell dialogShell) {
		this.dialogShell = dialogShell;
	}

	public final Table getTableData() {
		return tableData;
	}

	public final void setTableData(Table tableData) {
		this.tableData = tableData;
	}

	public final Text getFSearch() {
		return fSearch;
	}

	public final void setFSearch(Text search) {
		fSearch = search;
	}

	private final void tableDataMouseDoubleClick(MouseEvent evt) {
		if (!Util.isAllowedView(getFuncId())) {
			Util.showMsgBox("Anda tidak mempunyai hak untuk view data", 1,
					dialogShell);
			return;
		}

		showEditForm();
		if (Util.OPERATION_CODE > 0) {
			loadDataThread();
			Util.OPERATION_CODE = 0;
		}
	}

	private final void tableDataKeyPressed(KeyEvent evt) {
		if (evt.keyCode == 13) {
			if (!Util.isAllowedView(getFuncId())) {
				Util.showMsgBox("Anda tidak mempunyai hak untuk view data", 1,
						dialogShell);
				return;
			}

			showEditForm();
			if (Util.OPERATION_CODE > 0) {
				loadDataThread();
				Util.OPERATION_CODE = 0;
			}

		}
	}

	public final String deleteData() {
		TableItem[] items = tableData.getSelection();
		List<String> lst = new ArrayList<String>();
		if ((items == null) || (items.length < 1)) {
			Util.showMsgBox(AYConst.FAIL_DELETE, AYConst.MSG_WARN,
					getDialogShell());
		} else {

			try {
				MessageBox messageBox = new MessageBox(getDialogShell(), SWT.OK
						| SWT.CANCEL | SWT.ICON_WARNING);
				messageBox.setMessage("Anda Yakin akan menghapus data ini?");
				if (messageBox.open() == SWT.OK) {

					for (int j = 0; j < items.length; j++) {
						TableItem itm = (TableItem) items[j];
						String idDelete = itm.getText(0);
						lst.add(idDelete);
					}

					if (lst.size() > 0) {
						doDelete(lst);
						loadDataThread();
					}

				}
			} catch (Exception e) {
				e.printStackTrace();
				Util.showMsgBox("Data yg dipilih gagal dihapus!, karena: "
						+ e.getMessage(), 1, dialogShell);
			} finally {
				lst = null;
				System.out.println("list dinulkan ...");
			}
		}

		return "success";
	}

	private void fSearchKeyReleased(KeyEvent evt) {
		if (evt.keyCode == 13) {
			loadDataThread();
		}
	}

	private void btnClearWidgetSelected(SelectionEvent evt) {
		fSearch.setText("");
		loadDataThread();
	}

	public void getListObjFromJson(List<?> lst) {
		if (lst == null) {
			return;
		}
		tableData.setItemCount(lst.size());
		for (int j = 0; j < lst.size(); j++) {
			final TableItem item = tableData.getItem(j);
			if (j % 2 == 0) {
				item.setBackground(SWTResourceManager.getColor(217, 249, 208));
			} else {
				item.setBackground(SWTResourceManager.getColor(255, 255, 255));

			}
			Object obj = (Object) lst.get(j);
			fillTable(obj, item);
		}
	}

	private void btnExportWidgetSelected(SelectionEvent evt) {
		doExport();
	}

}
